import cn.igroup.service.push.proto.PushMsgOuterClass;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * @author LONG
 * @date 2018/1/8 15:37
 */
@ChannelHandler.Sharable
public class ClientHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("激活时间是：" + new Date());
        PushMsgOuterClass.PushMsg.Builder builder = PushMsgOuterClass.PushMsg.newBuilder();
        PushMsgOuterClass.MsgHeader.Builder builderHeader = PushMsgOuterClass.MsgHeader.newBuilder();
        builderHeader.setFormat(PushMsgOuterClass.MsgHeader.Format.STRING);
        builderHeader.setType(PushMsgOuterClass.MsgHeader.Type.LOGIN);

        builder.setId(System.currentTimeMillis());
        builder.setHeader(builderHeader.build());
        builder.setPayload(com.google.protobuf.ByteString.copyFromUtf8("userId.token"));
        ctx.writeAndFlush(builder.build());
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("停止时间是：" + new Date());
        System.out.println("HeartBeatClientHandler channelInactive");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof PushMsgOuterClass.PushMsg) {
            PushMsgOuterClass.PushMsg pushMsg = (PushMsgOuterClass.PushMsg) msg;
            System.out.println("id -> " + (pushMsg.getPayload().toStringUtf8()));
        }
        System.out.println(ctx.channel().remoteAddress() + "-> " + msg.toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

/*    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("循环触发时间：" + new Date());
        *//*if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                if (currentTime <= TRY_TIMES) {
                    System.out.println("currentTime:" + currentTime);
                    currentTime++;
                    ctx.channel().writeAndFlush(HEARTBEAT_SEQUENCE.duplicate());
                }
            }
        }*//*
    }*/

}
